package com.cbd.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baidu.aip.face.AipFace;
import com.cbd.common.FileStorageService;
import com.cbd.common.UserStatus;
import com.cbd.dto.UserLoginDto;
import com.cbd.entity.UserEntity;
import com.cbd.log.LogOut;
import com.cbd.log.OpLog;
import com.cbd.service.IUserService;
import com.cbd.util.FaceUtil;
import com.cbd.util.ResultResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Flowen~
 * @Date: 2024/11/22 10:48
 * @Description:用户控制器类
 */
@RestController
@Slf4j
@RequestMapping("/user")
@Api(tags = "用户接口")
public class UserController {
    /**
     * 文件储存服务
     */
    private final FileStorageService fileStorageService;

    public UserController(FileStorageService fileStorageService) {
        this.fileStorageService = fileStorageService;
    }

    /**
     * 服务对象
     */
    @Resource
    private IUserService userService;

    /**
     * 用户注册
     *
     * @param users 用户对象
     * @return 注册结果
     */
    @PostMapping("/register")
    @ApiOperation(value = "用户注册", notes = "用户注册接口")
    public ResponseEntity<?> register(
            @ApiParam(name = "users", value = "用户对象", required = true)
            @RequestBody UserEntity users) {
        boolean success = userService.register(users);
        if (success) {
            return ResponseEntity.ok().body("注册成功");
        } else {
            return ResponseEntity.badRequest().body("注册失败：用户名已存在");
        }
    }

    /**
     * 用户登录
     *
     * @param userLoginDto 用户登录对象
     * @return 登录结果
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "用户登录接口")
    @OpLog(type = "登录", info = "进行了登录")
    public ResponseEntity<?> login(
            @ApiParam(name = "users", value = "用户对象", required = true)
            @RequestBody UserLoginDto userLoginDto) {
        log.info("用户{}进行登录", userLoginDto.getUsername());
        boolean user = userService.login(userLoginDto);
        if (user) {
            StpUtil.login(userLoginDto.getUsername()); //用来获取用户权限
            log.info("用户{}登录成功", userLoginDto.getUsername());
            // 在登录成功后，检查用户状态
            UserStatus userStatus = userService.checkUserStatus(userLoginDto.getUsername());
            Map<String, Object> response = new HashMap<>();
            response.put("message", "登录成功");
            response.put("status", userStatus);
            return ResponseEntity.ok(response);
        } else {
            log.info("用户{}登录失败", userLoginDto.getUsername());
            return ResponseEntity.badRequest().body("登录失败：用户名或密码错误");
        }
    }

    @PostMapping("/logout")
    @ApiOperation(value = "用户退出", notes = "用户退出接口")
    @LogOut(type = "注销", info = "进行了注销")
    public ResultResponse<String> logout() {
        String username = StpUtil.getLoginIdAsString(); //获取当前登录的账号
        StpUtil.logout(); //退出登录
        log.info("用户{}已退出登录", username);
        return ResultResponse.success("退出登录成功");
    }

    /**
     * 检查用户状态
     *
     * @param username 用户名
     * @return 用户状态
     */
    @GetMapping("/checkUserStatus")
    @ApiOperation(value = "检查用户状态", notes = "检查用户状态接口")
    public UserStatus checkUserStatus(
            @ApiParam(name = "username", value = "用户名", required = true)
            @RequestParam String username) {
        return userService.checkUserStatus(username);
    }

    /**
     * 实名认证
     *
     * @param username 实名认证对象名
     *                 cardImage 身份证照片
     *                 confirmImage 确认照片
     * @return 实名认证结果
     */
    @PostMapping("/realNameAuth")
    @ApiOperation(value = "实名认证", notes = "实名认证接口")
    public ResponseEntity<?> realNameAuth(
            @ApiParam(name = "username", value = "实名认证对象名称", required = true)
            @RequestParam("username") @NotNull @Size(min = 1) String username, //确保用户名不为空并且长度大于1
            @RequestPart("cardImage") MultipartFile cardImage,
            @RequestPart("confirmImage") MultipartFile confirmImage) {
        try {

            // 使用文件储存服务来保存文件
            String cardImagePath = fileStorageService.storeFile(cardImage);
            String confirmImagePath = fileStorageService.storeFile(confirmImage);

            // 调用人脸识别接口进行验证
            FaceUtil faceUtil = new FaceUtil();
            AipFace aipFace = new AipFace("116323232", "DWDDkE3xcBmSO9mOWeOmtUiJ", "B4TQPDn7Eu4zatoXhhn9m17S1JdFscf7");
            double result = faceUtil.faceUtils(aipFace, cardImagePath, confirmImagePath);

            if (result >= 75) {
                // 人脸识别成功
                log.info("用户{}人脸识别成功，得分为{}", username, result);
                boolean status = userService.updateUserStatus(username);
                if (status) {
                    UserStatus userStatus = userService.checkUserStatus(username);
                    log.info("用户{}实名认证成功，用户状态为{}", username, userStatus);
                    return ResponseEntity.ok().body("实名认证成功");
                } else {
                    log.info("用户{}实名认证失败，更新用户状态失败", username);
                    return ResponseEntity.badRequest().body("实名认证失败：更新用户状态失败");
                }
            } else {
                log.info("用户{}实名认证失败，人脸识别失败", username);
                return ResponseEntity.badRequest().body("实名认证失败：人脸识别失败");
            }
        } catch (IOException e) {
            log.error("文件保存失败：{}", e.getMessage());
            return ResponseEntity.badRequest().body("实名认证失败：文件保存失败");
        } catch (Exception e) {
            log.error("实名认证过程中发生异常：{}", e.getMessage());
            return ResponseEntity.badRequest().body("实名认证失败：发生错误，请稍后重试");
        }
    }


}
